package com.sakura.handler;

import com.sakura.util.R;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @author : Sakura
 * @Date : 2023/11/22 20:02
 * @Description : TODO 参数校验异常类
 */
@RestControllerAdvice(basePackages = "com.sakura.controller")
public class ExceptionControllerAdvice {
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException exception){
        BindingResult result = exception.getBindingResult();
        Map<String,String> map = new HashMap<>();
        result.getFieldErrors().forEach(item->{
            String field = item.getField();
            String message = item.getDefaultMessage();
            map.put(field,message);
        });
        return R.error("数据校验异常").setData(map);
    }
}
